from django.shortcuts import render
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import permission_required
from ..models import Users
# 导入密码加密
from django.contrib.auth.hashers import make_password, check_password
# 上传 头像
from . IndexViews import uploads
from lzy.settings import BASE_DIR
import os
# 用户添加 显示显示添加首页
def useradd(request):
    
    return render(request,'admin/users/add.html')


#执行用户的数据添加
@permission_required('myadmin.insert_users',raise_exception = True)
def userinsert(request):
    # try:
        # 接收表单数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    # 密码加密
    data['password'] = make_password(data['password'],None,'pbkdf2_sha256')

    # 是否上传了头像
    myfile = request.FILES.get('pic',None)
    # 判断是否有文件上传
    if myfile:
        # 有文件上传
        from . IndexViews import uploads
        data['pic'] = uploads(myfile)
    else:
        # 没有文件上传
        data['pic'] = '/static/pics/users.jpg'

    # 创建用户
    Users.objects.create(**data)

        # 跳转到列表页
    return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    # except:
    return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_user_add')+'"</script>')
    # return  HttpResponse(dfasd)


# 列表
@permission_required('myadmin.show_users',raise_exception = True)
def userindex(request):

    # 读取数据
    users = Users.objects.exclude(status=2)

    # 接受参数
    types = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None)
    # 判断是否有搜索条件
    if types:
        if types == 'all':
        # 多字段的查询
            from django.db.models import Q
            users = users.filter(Q(username__contains=keywords)|Q(email__contains=keywords)|Q(phone__contains=keywords)|Q(age__contains=keywords))
        else:
            data ={types+'__contains':keywords}
            users = users.filter(**data)
# ----------------------------------------------
    # if types:
    #     if types == 'all':
    #         # 多字段的查询
    #         # select * from users where username like '%aa%' or age like '%aa%' or
    #         from django.db.models import Q
    #         users = users.filter(Q(username__contains=keywords)|Q(email__contains=keywords)|Q(phone__contains=keywords)|Q(age__contains=keywords))
    #     else:
    #         data = {types+'__contains':keywords}
    #         users = users.filter(**data)


    # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(users,10)
    # 获取当前的页码数
    page = request.GET.get('page',1)
    # 获取当前页的数据
    userlist = p.page(page)
    # 获取所有的页码列表
    pages = p.page_range

    # 分配数据
    context = {'users':userlist}

    # 加载模板
    return render(request,'admin/users/index.html',context)

# 删除
@permission_required('myadmin.del_users',raise_exception = True)
def userdelete(request,uid):
    try:
        # 根据id用户获取对象
        ob = Users.objects.get(id=uid)
        # 修改状态
        ob.status = 2
        # 执行
        ob.save()
        # 操作成功
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    except:
        # 操作失败
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_user_index')+'"</script>')


# 编辑
@permission_required('myadmin.edit_users',raise_exception = True)
def useredit(request,uid):
    # 根据id用户获取对象
    ob = Users.objects.get(id=uid)

    # 分配数据
    context = {'uinfo':ob}

    # 返回模板页面
    return render(request,'admin/users/edit.html',context)


# 修改
@permission_required('myadmin.edit_users',raise_exception = True)
def userupdate(request):
    try:
        # 接收数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        # 获取对象
        ob = Users.objects.get(id=data['id'])
        # 更新属性
        ob.username = data['username']
        ob.password = data['password']
        ob.phone = data['phone']
        ob.email = data['email']
        ob.sex = data['sex']
        ob.age = data['age']

        # 判断是否有文件上传
        myfile = request.FILES.get('pic',None)
        if myfile:
            # 有文件上传,删除原有头像数据
            # 判断是否使用,默认头像
            # if ob.pic != '/static/pics/users.jpg':
                # 删除原来的头像
                # os.remove(BASE_DIR+ob.pic)
            # 执行文件上传,并更新头像数据
            ob.pic = uploads(myfile)
        # 执行更新    
        ob.save()
        # 操作成功
        return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myadmin_user_index')+'"</script>')
    except:
        # 操作失败
        return HttpResponse('<script>alert("更新失败");location.href="'+reverse('myadmin_user_index')+'"</script>')

        # return HttpResponse("/myadmin/user/index/")